_hottouse.GIF (2162 bytes)
 _question.gif (70 bytes)  Tutorials --> JavaScript 1.2 --> Intro 
JavaScript is a simple programming language that has unlimited uses and has become more popular on personal websites. You have most likely experienced JavaScript: scrolling text, light up images, press in buttons, etc. JavaScript is a scripting language and does not require a complier. By learning this language you as a web designer can make your website more useful and decorative.

JavaScript is not Java. Although there is a similarity in naming, Java is a more powerful language which requires a complier. JavaScript is used exclusively on the web, where as Java can be used to created software programs.

Netscape Communications invented JavaScript under the name Livescript. The language is heavily influenced by other languages (C, Perl) but was made for usage on the internet using Netscape 2. JavaScript became popular and a 1.1 version was released with Netscape 3. Microsoft released a rough version of JavaScript, referred to as JScript, for its internet explorer. Currently both Netscape & Microsoft are moving toward an ECMAScript merger so that JavaScript works the same in future versions of both browsers.

In order to program in JavaScript you need knowledge of HTML (obviously). If you have experience in languages such as C, Java, Visual Basic, and Pascal, JavaScript will seem relatively easy. The only necessary tools are a web browser (Netscape 3+, IE 3+) and a plain editor. If you use an HTML editor, you must check to see if it supports JavaScript.

99% of the time, JavaScript is written inside the <HEAD> tags. Here is the most simple example of the placement of a JavaScript:


<HTML>
<HEAD>
JavaScript Testing Page
<SCRIPT LANGUAGE="JavaScript">
  // JavaScript Here
</SCRIPT>
</HEAD>
</HTML>

Please note also that the JavaScript is held in the </SCRIPT> tag. When writing a script, you can use // to add messages that the browser will ignore. Sounding easy?

 

 _question.gif (70 bytes)  Java Scripts Basics?
So you're ready to learn how to write your first JavaScript? Well before you learn the language, you should know how it works. Scripts placed within <SCRIPT> tags are evaluated after the page loads. Functions are stored, but not executed. In fact, functions are executed by events in the page.

It's important to understand the difference between defining a function and calling the function. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters.

If you are confused, don't be. It really isn't as difficult as it sounds.


<HEAD>
<SCRIPT LANGUAGE="JavaScript">
    function square(i) {
    document.write("The call passed ", i ," to the function.","<BR>")
    return i * i  }  document.write("The function returned ",square(2),".")
</SCRIPT>
</HEAD>

If you were to put this in your HTML document, it would be seen in your browser as:We passed 2 to the function. The function returned 4. This is a simple script which defines 2 as a function, then orders the browser to double the size of the fuction by using return i * i The reason you see We passed 2 to the function. The function returned 4. is because of document.write, which orders the browser to write the results.

The function document.write is used in just about any JavaScript you write. The example of JavaScript printing Hello, World! is shown below:


<BODY>
<SCRIPT LANGUAGE="JavaScript">
    document.write('Hello, World!');
</SCRIPT>
</BODY>

This function is held in the <BODY> tag rather than in the <HEAD> tag. document.write is known as a host function and all web browsers supporting JavaScript will display this simply as the text Hello, World!.

In JavaScript, you can create an INPUT/OUTPUT function in 3 simple, effective ways. By changing document.write('Hello, World!'); to alert('Hello, World!');, you can alert your visitor with a popup button which forces the user to click OK in order to continue. The other 2 are confirm('Enter?'); which forces a user to either click OK and continue or cancel and leave, and prompt('Your name is?'); which allows the visitor to type into a textbox.

Please keep this in mind for later in the tutorial. Now, let us focus on storing information inside JavaScript code using variables & or directly in constants. A variable begins with var and is stored directly in the script. You'll find most of your scripting trouble held within variables because of its exactness. If you use an unknown character in one, your entire script will not work.

JavaScript is a loosely typed language meaning that variables do not necessarily have a defined variable type. Each variable can hold values of various types. This may all sound weird to the total non programmer, but its easy once you experiment with it.


var x= 10;
var y= "11";
var y= '11';

var z= 1 + y;

document.write(x);

This example shows basically one of several things variables can do. This is obviously simple addition. By defining variables, you can write them using document.write(x); (where x is your var name) or call them from further in your script.

The simple building blocks in all data of JavaScript are known as the primitive types. These are as follows:

  • Strings: "Hello World!"
  • Numbers: Integers (1, 50) & Decimals (1.5, 50.1)
  • boolean: True or False

JavaScript will recognize the following special characters. This idea derived from the C programming language:

  • \n - newline
  • \t - tab
  • \f - form feed
  • \b - backspace
  • \r - carriage return

In addition to the 3 primitive types, there are 3 less obvious ones:

  • NaN - Not a Number; a result of a math operation gone wrong.
  • null - No Data. Nothing has been stored in the variable.
  • undefined - No Data. Usually bad; error in your script.

Now that you have some background on variables, we introduce the array. An array lets you store multiple pieces of data in the same variable. Using arrays allows you to put all similar variables under 1 name, rather than name them all separately.

In JavaScript 1.2, the statement new Array creates a new array set to a specific value. This allows you to create an array with several elements by listing them in brackets:


arrayName = [element0, element1, ..., elementn]

In this example arrayName is the name of the new array & elementn is a list of values for the array's elements.

Arrays can expand in the number of size and are quite flexible compared to arrays used in C. Another trick with an array is placing an array element in another array. This opens an unlimited amount of uses in mathematics and graphics.

Now in the next section, we'll look futher into functions and we'll meet statements, objects, operators, & type conversation. Ready?

 

A JavaScript consists of a sequence of statements. Statements is to a JavaScript as a plot is to a story. All JavaScripts must have statements to exist. Statements are read from top to bottom unless the script tells it otherwise. Scripters usually use something called comments to describe a statement. Usually, they use comments to help someone viewing their script, bringing them through it step by step.

A block is a collection of statements. The browser can read a block as one statement, even though it is a collection of statements.


{
clib.put('The value is')			// Comment 1
clib.put{'15')					// Comment 2
}
	/* another comment right here

Here we see a statement clib.put('The value is'). Now notice { & }. This is a block; just as defined, a collection of statements. This one only contains 2 statements, but this is just and example. This example also introduces // Comment which includes comments for anyone viewing the source to read. This will not be picked up by the browser. You can either use // or /*.

Please note we are just introducing basic commands the language uses. We do not expect you to memorize this information, but you must be familiar with it. We will soon tell you how this all fits together.

 

 

 

_question.gif (70 bytes)  Image Rollover?
An image rollover is the most loved JavaScript effect. We recieve more questions about rollovers alone, then any other script. The image rollover saved the name of JavaScript by erasing the bad name scrolling text gave the language. This trick will change the graphic when the mouse is moved over it.

When creating an image rollover, you need at least 2 different graphics; the one that loads with your webpage and the one that loads when the mouse is moved over the original image. In our example there is a total of 8 different images.


img1on = new Image();           // Active images
img1on.src = "image1on.gif";  
img2on = new Image(); 
img2on.src = "image2on.gif";  
img3on = new Image();
img3on.src = "image3on.gif";
img4on = new Image();
img4on.src = "image4on.gif";

img1off = new Image();          // Inactive images
img1off.src = "image1off.gif"; 
img2off = new Image();
img2off.src = "image2off.gif";  
img3off = new Image();
img3off.src = "image3off.gif";
img4off = new Image();
img4off.src = "image4off.gif";

Above you see the images called within your javascript. The first image objects called begin with img1on and run through img4on. All of the beginning image objects have the same suffix; on. The second image objects called begin with img1off and run through img4off. They share the suffix off. You do not need to name your gifs these particular names, but it is recommended because they keep them organized.

In our example, img1on is the active image (the one which is first seen) and img1off is the image which is seen when the mouse is moved over the first image. Once you have all your images set in the script, you are ready to call the actual rollover in the links on your page.


<A HREF = "yourlink.html" onMouseOver = "imgOn('img1')"
onMouseOut = "imgOff('img1')">
<IMG NAME = "img1" SRC = "image1off.gif"></A>

When calling an image rollover script, you use event handlers passing two functions onMouseOver and onMouseOut. onMouseOver runs the imgOn() function when the mouse is moved over the active image:


function imgOn(imgName) {
   if (document.images) {
       document[imgName].src = eval(imgName + "on.src");
        }
}

This function passes the name of the image to the variable imgName. Then adds on as a suffix to the graphic name. When the on suffix is added to the name, the result is the name of the active graphic img1). The same function is used when the mouse is moved off of the image. The imgOff() function is run:


function imgOff(imgName) {
        if (document.images) {
            document[imgName].src = eval(imgName + "off.src");
        }
}

That is the mystery behind that amazing rollover function in JavaScript. We have a second tutorial on an alternative way to do image rollovers. Please read below; this script checks the browser before loading and preloads the graphics. It is a bit more complicated.

 

There are many ways to do an image rollover. In this example, we see that the JavaScript preloads the images, where in the first, the images must load when the mouse passes over. This example also does a browser check to make sure the browser supports the script.

The first thing you should do is have a browsercheck. The best browsercheck when we're doing a rollover is if(document.images). This checks if the browser supports the image object. The reason we do this is because there might come (I know Opera4 that comes later this spring will support it) browsers other then ns and ie that supports this, and its much easier then that navigator.appname==3.

Then next thing you should do is preload the images. First "make" a new image object with the new Image() function myimage=new Image(). Then set the src property for the image object. The src property works as in regular HTML. (myimage.src='myimage.gif')

Do I have to do that for every image you ask? Since we are very nice we have made a preloading function for you so you wont have to do that!

To make it easy to follow the rest of this tutorial you should name you images like this: You make 5 images, name them norm1.gif norm2.gif and so on. And 5 images that the norm image will change to when you mouseover, name them over1.gif over2.gif and so on. Then place all the images in a folder named images. (you can change this later if you wish)


function PreloadImages(length, path, type)
{
    for(var i = 1; i<=length; i++) {
        this[i]= new Image()
        this[i].src= path + i + type
    }
    return this
} 

The function used above will preload the images. We call it with the line norm=new PreloadImages(5,'images/norm','.gif'). "norm" is the name of the array we make, "5" is the number of pics we have, "images/norm" is the path where the images is and the name of the image and ".gif" is the imagetype. This will make the images be like this: norm[1].src='images/norm1.gif and so on. Now we have to preload the over images. We do that using over=new PreloadImages(5,'images/over','.gif').

There is how to preload the images in a nutshell. If you have more then five pictures or other names on the pictures just change it in those calling lines.(example: you have 15 images, they are in the same folder as the html document, and they are named hello1.jpg hello2.jpg and so on. The line would then be: hello=PreloadImages(15,'hello','.jpg'))

Here is the functions that will switch the images (we will name the images in page later):


function rollOn(num){
    if(document.images){
        eval('document.images["norm'+num+'"].src
            ='+'over[num].src')}
}

That function is the one that changes the norm image to the over image when you mouseover. Lets go line by line:

  • function rollOn(num){ - This line contains the name of the function and the argument num that we will pass when we call the function.
  • if(document.images){ - This is the browsercheck. If the users browsers doesn't support the imagearray nothing will happen in this function.
  • eval('document.images["norm'+num+'"].src ='+'over[num].src')} - This line uses the eval function to execute strings.
  • document.images - The way to reach the image; the image is a image (obviously) and its on the document.
  • document.images - The name of the image, I know we haven't named them yet but we will.
  • over[num].src - The image that we placed in the src property of the over array earlier.

And here is the rollout function:


function rolloff(num){
if(document.images)
    eval('document.images["norm'+num+'"].src='
            +'norm[num].src')
}

This function does basically the same thing only the other way around.

Now lets make the page that the script will run on:

<HTML>
<HEAD>
    <TITLE>Mouseover</TITLE>
</HEAD>
<BODY>
<a href="#" onmouseover="rollOn(1)" onmouseout="rolloff(1)">
<img src="../images/norm1.gif" name="norm1" border="0"></a>
<a href="#" onmouseover="rollOn(2)" onmouseout="rolloff(2)">
<img src="../images/norm2.gif" name="norm2" border="0"></a>
<a href="#" onmouseover="rollOn(3)" onmouseout="rolloff(3)">
<img src="../images/norm3.gif" name="norm3" border="0"></a>
<a href="#" onmouseover="rollOn(4)" onmouseout="rolloff(4)">
<img src="../images/norm4.gif" name="norm4" border="0"></a>
<a href="#" onmouseover="rollOn(5)" onmouseout="rolloff(5)">
<img src="../images/norm5.gif" name="norm5" border="0"></a>
</BODY>
</HTML>

As you can see we name the images; norm1, norm2, norm3, norm4 and norm5. And we call the rollOn function on mouseover and the rollOff function on mouseout. The link point to # which really just means the top of the page.

Now we have to put in the finished script:

<script language="javascript">
<!--//Hiding from old browsers
function PreloadImages(length, path, type) {
    for(var i = 1; i<=length; i++) {
        this[i]= new Image()
        this[i].src= path + i + type
    }
    return this
}

over=new PreloadImages(5,'../images/over','.gif')
norm=new PreloadImages(5,'../images/norm','.gif')

function rollOn(num){
if(document.images)
    eval('document.images["norm'+num+'"].src='+'over[num].src')
}
function rolloff(num){
if(document.images)
    eval('document.images["norm'+num+'"].src='
            +'norm[num].src')
}

//-->end hiding
</script>

Just place this between the head tag in the page and your set!

 

_question.gif (70 bytes)  Java Reference?
This can be called the Appendix of our JavaScript tutorial. This guide defines all major input/output, fuctions, & objects. Please select a version of JavaScript to view its reference card.

In the reference section, superscripts indicate what version the feature was first implemented in. Red subscripts indicate which versions have known problems with the feature. NS stands for Netscape and IE stands for Microsoft Internet Explorer.

JavaScript NS2

  • <script language="JavaScript">
  • Runs script only if browser supports language version.

JavaScript1.1 NS3 NS2 IE3

  • <script language="JavaScript1.1">
  • Runs script only if browser supports language versi on.

JavaScript1.2 NS4 NS2 NS3 IE3

  • <script language="JavaScript1.2">
  • Runs script only if browser supports language v ersion.

JScript1.1 IE4 NS2 NS3 NS4 IE3

  • <script language="JScript1.1">
  • Runs script only if browser supports language version.
  • IE3: Version of JScript implemented on IE3 but IE3 does not recognize attribute.

JScript1.2 IE4 NS2 NS3 NS4 IE3

  • <script language="JScript1.2">
  • Runs script only if browser supports language version.

 

 _question.gif (70 bytes)  Manipulate Windows?
A main use for JavaScript is to manipulate windows and frames to make your site more easy to navigate through and so forth. A window object can be handled by a JavaScript object called window, wherreas a document object can always be opened by a JavaScript object called document. This part of our tutorial will get you more familar with JavaScript capabilities with windows and frames.

Obviously, you know a browser can open more than one window at once. Each window is represented by a Window object in JavaScript. Using JavaScript, you can have full control of opening new windows. The simplest way to open a new window is using open(). This is an important function. It can be used in several ways. Below is a simple way to open a new window using JavaScript and the open() function:


var win1="open(newwindow.html");

function new_win()

Then call it in your HTML document like so:


Open New Window

By using a # in the tag, you prevent a page from being replaced when a link is followed. Now you can open more than 1 window at a time and specify the size of the window your opening.


var win1="open(newwindow.html" "resizable=no,height=500,width=500");

function new_win()
{
var win1="open(newwindow2.html" "resizable=no,height=100,width=100");
}

This will open 2 windows; one window smaller then the other. This is quite simple and can be done for any amount of windows.

The open() function is very powerful; it provides the new window with a name and a set of window property options. Please note, the arguments to open() must be comma-separated, not space separated. In order to pop up windows without a user clicking (I must warn, can be extremely annoying!) is to not call a function. Just use:


variable-name = open("url, "windowname", 
"resizeable=no,height=100, width=100");

This is usually a bad for 2 major reasons. When the function ends and the variable goes, you loose track of the new window. It is better to keep the variable permanent, incase you want to use it again. Also, people do NOT appreciate unexpected windows popping up all over (ie Geocities, Tripod).